package userapp

import (
	"fmt"
	"net/http"
	"protection/user/types"
	userredis "protection/user/user_redis"
	"strconv"
	"strings"
	"time"

	myrpc "github.com/2217263633/kakarpc"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"golang.org/x/crypto/bcrypt"
)

// @BasePath /api/v1
// PingExample godoc
// @Summary 获取用户
// @Schemes
// @Description
// @Param user_id query int true "用户id"
// @Security Authorization
// @Tags 用户系统
// @Accept json
// @Produce json
// @Router /user [get]
func GetUser(c *gin.Context) {
	user_id := c.Query("user_id")
	if user_id == "" {
		myrpc.DetailErr("参数错误", c)
		return
	}
	_, err := types.ParseSign("44872", c.GetHeader("Authorization"))
	if err != nil {

		myrpc.DetailErr("用户token错误", c)
		return
	}
	// logger.Info(myrpc.CallAny(&Rpc, "MysqlService.NoSome", c.GetHeader("Authorization")+"4564", "数据库调用"))
	res, err := myrpc.QuerySql(&Rpc, "select * from user where id="+user_id)
	c.JSON(http.StatusOK, gin.H{"data": res, "err": err})
}

// @BasePath /api/v1
// PingExample godoc
// @Summary 登陆
// @Schemes
// @Description
// @Param data body types.LoginForm true "用户id"
// @Security Authorization
// @Tags 用户系统
// @Accept json
// @Produce json
// @Router /login [post]
func PostLogin(c *gin.Context) {
	var form types.LoginForm
	err := c.ShouldBind(&form)
	if err != nil {
		myrpc.DetailErr(err.Error(), c)
		return
	}
	sql := fmt.Sprintf(`select * from user where email='%s'`, form.Email)
	res, err := myrpc.QuerySql(&Rpc, sql)
	if err != nil {
		myrpc.DetailErr(err.Error(), c)
		return
	}

	ownVal := make(map[string]interface{})
	if len(res) == 0 {
		c.JSON(401, gin.H{"data": "无法找到账号"})
		return
	}
	// 获取验证码
	codeId := form.CodeId
	code := form.Code
	redisCode, err := userredis.CusRedisClient.RedisDB.Get(c, types.CodePrefix+codeId).Result()
	if err != redis.Nil && err != nil {
		myrpc.DetailErr("服务器错误", c)
		return
	}
	if !strings.EqualFold(code, redisCode) {
		c.JSON(401, gin.H{"data": "验证码错误"})
		return
	}
	userIdStr := strconv.Itoa(int(res[0]["id"].(float64)))
	var count int

	val, err := userredis.CusRedisClient.RedisDB.Get(c, userIdStr).Result()

	if err != redis.Nil && err != nil {
		myrpc.DetailErr("服务器错误", c)
		return
	}

	if err == redis.Nil {
		_, err = userredis.CusRedisClient.RedisDB.Set(c, userIdStr, 1, types.AccountExpireTime).Result()
		if err != nil {
			myrpc.DetailErr("服务器错误", c)
			return
		}
	}
	if val != "" {
		count, err = strconv.Atoi(val)
		if err != nil {
			myrpc.DetailErr("服务器错误", c)
			return
		}
		if count >= types.DefaultAccountCount {
			c.JSON(401, gin.H{"data": "请五分钟后重新登陆"})
			return
		}
	}

	userId := res[0]["id"].(float64)
	password := res[0]["password"].(string)
	// logger.Info(userId, password)
	err = bcrypt.CompareHashAndPassword([]byte(password), []byte(form.Password))
	if err != nil {
		_, err := userredis.CusRedisClient.RedisDB.Incr(c, userIdStr).Result()
		if err != nil {
			myrpc.DetailErr("服务器错误", c)
			return
		}
		c.JSON(401, gin.H{"data": "密码错误"})
		return
	}

	var a types.LoginStruct = types.LoginStruct{
		ID:       int(userId),
		Username: form.Email,
		Source:   form.Source,
	}

	queryCompanySql := fmt.Sprintf(`select id from organ where name='%s'`, form.Company_name)
	// // logger.Info(queryCompanySql)
	queryResu, _ := myrpc.QuerySql(&Rpc, queryCompanySql)
	if len(queryResu) > 0 {
		ownVal["company_id"] = queryResu[0]["id"]
	}
	ownVal["email"] = res[0]["email"]
	ownVal["id"] = userId
	ownVal["headimg"] = res[0]["headimg"]
	ownVal["name"] = res[0]["name"]
	ownVal["person_sign"] = res[0]["person_sign"]
	ownVal["phone"] = res[0]["phone"]
	ownVal["handle_sign"] = res[0]["handle_sign"]
	ownVal["faceimg"] = res[0]["faceimg"]
	ownVal["sex"] = res[0]["sex"]
	ownVal["id_card"] = res[0]["id_card"]
	ownVal["nation"] = res[0]["nation"]
	ownVal["body_height"] = res[0]["body_height"]
	ownVal["body_weight"] = res[0]["body_weight"]
	ownVal["native_place"] = res[0]["native_place"]
	ownVal["marital_status"] = res[0]["marital_status"]
	ownVal["politics_status"] = res[0]["politics_status"]
	ownVal["health_condition"] = res[0]["health_condition"]
	ownVal["blood_type"] = res[0]["blood_type"]
	ownVal["education"] = res[0]["education"]
	ownVal["school"] = res[0]["school"]
	ownVal["technical_grade"] = res[0]["technical_grade"]
	ownVal["major"] = res[0]["major"]
	ownVal["home_adress"] = res[0]["home_adress"]
	ownVal["adress"] = res[0]["adress"]

	token, err := types.Sign(a, "44872")
	if err != nil {
		myrpc.DetailErr("服务器错误", c)
		return
	}
	refreshToken, err := types.SignExp(a, "44872", time.Now().Add(time.Hour*types.RefreshTokenTimeHour).Unix())
	if err != nil {
		myrpc.DetailErr("服务器错误", c)
		return
	}

	c.JSON(200, gin.H{"token": token, "refreshToken": refreshToken, "id": ownVal})
}
